using UnityEngine;
using TEngine;
using System;
using System.Collections.Generic;
using System.Linq;

namespace GameLogic
{
    /// <summary>
    /// 矩阵控制核心类
    /// </summary>
    public class MatrixCtrl : MonoBehaviour 
    {
        #region 组件
        private RectTransform _rectSelf;
        #endregion
        
        #region 矩阵属性
        private int _rows;
        private int _columns;
        private float _cellWidth;
        private float _cellHeight;
        private Dictionary<Vector2Int, CellCtrl> _cellsDict = new Dictionary<Vector2Int, CellCtrl>();
        private bool _isAnimationEnabled = true; // 默认启用动画

        /// <summary>
        /// 是否启用矩阵整理动画
        /// </summary>
        public bool EnableAnimation
        {
            get => _isAnimationEnabled;
            set => _isAnimationEnabled = value;
        }

        /// <summary>
        /// 当前矩阵行数
        /// </summary>
        public int Rows => _rows;

        /// <summary>
        /// 当前矩阵列数
        /// </summary>
        public int Columns => _columns;

        /// <summary>
        /// 单元格宽度（单位：像素）
        /// </summary>
        public float CellWidth => _cellWidth;

        /// <summary>
        /// 单元格高度（单位：像素）
        /// </summary>
        public float CellHeight => _cellHeight;

        #endregion

        #region 初始化
        /// <summary>
        /// 初始化矩阵参数
        /// </summary>
        /// <summary>
        /// 初始化矩阵并加载单元格
        /// </summary>
        /// <summary>
        /// 初始化矩阵并加载单元格
        /// </summary>
        public void Initialize<TCtrl>(int rows, int columns, RectTransform rectSelf, string cellPrefabPath ,int cellsNum = 0) where TCtrl : CellCtrl
        {
            // 初始化组件引用（带错误检查）
            _rectSelf = rectSelf != null ? rectSelf : GetComponent<RectTransform>();
            if (_rectSelf == null)
            {
                Log.Error("RectTransform引用缺失！请检查：\n" +
                         "1. 传入的rectSelf参数是否有效\n" +
                         "2. 父物体是否包含RectTransform组件");
                return;
            }
            
            // 校验输入参数
            if (rows <= 0 || columns <= 0)
            {
                Log.Error($"无效的矩阵尺寸: {columns}列×{rows}行");
                return;
            }

            // 设置矩阵基础属性
            _rows = rows;
            _columns = columns;
            var parentSize = _rectSelf.rect.size;
            _cellWidth = parentSize.x / columns;
            _cellHeight = parentSize.y / rows;

            // 预计算总单元格数
            int totalCells = rows * columns;
            _cellsDict.Clear();

            try
            {
                // 批量创建单元格
                for (int y = 0; y < rows; y++)
                {
                    for (int x = 0; x < columns; x++)
                    {
                        int index = y * columns + x;
                        if (cellsNum >0 && index > cellsNum)
                        {
                            break;
                        }
                        var cellPos = new Vector2Int(x, y);
                        
                        // 实例化单元格
                        var cellGo = GameModule.Resource.LoadGameObject(cellPrefabPath, _rectSelf);
                        if (cellGo == null)
                        {
                            Log.Error($"单元格预制体加载失败: {cellPrefabPath}");
                            continue;
                        }

                        // 获取控制器组件
                        var cellCtrl = cellGo.GetComponent<TCtrl>();
                        if (cellCtrl == null)
                        {
                            Log.Error($"单元格控制器组件缺失: {cellPrefabPath}");
                            continue;
                        }

                        // 初始化单元格（这里示例使用随机数值，实际应根据游戏逻辑设置）
                        InitializeCell(cellGo, cellCtrl, cellPos);
                        _cellsDict[cellPos] = cellCtrl;
                    }
                }

                Log.Info($"矩阵初始化完成: {columns}列×{rows}行\n" +
                        $"父容器尺寸: {parentSize}\n" +
                        $"单元格尺寸: {_cellWidth:F2}x{_cellHeight:F2}\n" +
                        $"总单元格数: {totalCells}");
            }
            catch (Exception e)
            {
                Log.Error($"矩阵初始化异常: {e}");
            }
        }

        /// <summary>
        /// 初始化单个单元格
        /// </summary>
        private void InitializeCell<TCtrl>(GameObject cellGo, TCtrl cellCtrl, Vector2Int cellPos) where TCtrl : CellCtrl
        {
            cellGo.name = $"Cell_{cellPos.x}_{cellPos.y}";
            
            // 初始化单元格控制器
            cellCtrl.InitCell(cellPos, _rectSelf);
            cellCtrl.SetSize(_cellWidth, _cellHeight);
            cellCtrl.SetPos(cellPos);

            // 设置单元格层级顺序（按行优先）
            cellGo.transform.SetSiblingIndex(cellPos.y * _columns + cellPos.x);
        }

        /// <summary>
        /// 获取所有单元格控制器
        /// </summary>
        public TCtrl[] GetAllCells<TCtrl>() where TCtrl : CellCtrl => new List<TCtrl>(_cellsDict.Values.OfType<TCtrl>()).ToArray();

        /// <summary>
        /// 根据坐标获取单元格
        /// </summary>
        public TCtrl GetCell<TCtrl>(Vector2Int gridPos) where TCtrl : CellCtrl
        {
            if (!IsValidGridPosition(gridPos)) return null;
            return _cellsDict.TryGetValue(gridPos, out var cell) ? (TCtrl)cell : null;
        }
        #endregion

        #region 坐标转换
        /// <summary>
        /// 将屏幕坐标转化为网格坐标（带边界检查和坐标修正）
        /// </summary>
        public bool ScreenToGrid(Vector2 screenPos, out Vector2Int gridPos)
        {
            // 根据Canvas渲染模式获取正确的Camera引用
            var canvas = _rectSelf.GetComponentInParent<Canvas>();
            Camera eventCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera;

            // 提前检查屏幕坐标是否在容器范围内
            if (!RectTransformUtility.RectangleContainsScreenPoint(_rectSelf, screenPos, eventCamera))
            {
                gridPos = Vector2Int.zero;
                return false;
            }

            // 将屏幕坐标转换为本地坐标（考虑父容器的实际位置和缩放）
            if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(
                _rectSelf, 
                screenPos, 
                eventCamera, 
                out var localPos))
            {
                gridPos = Vector2Int.zero;
                return false;
            }

            // 计算网格坐标（考虑父容器的锚点位置）
            int gridX = Mathf.FloorToInt((localPos.x + _rectSelf.pivot.x * _rectSelf.rect.width) / _cellWidth);
            int gridY = Mathf.FloorToInt((localPos.y + _rectSelf.pivot.y * _rectSelf.rect.height) / _cellHeight);

            gridPos = new Vector2Int(gridX, gridY);
            
            return IsValidGridPosition(gridPos);
        }

        /// <summary>
        /// 判断网格坐标是否有效
        /// </summary>
        public bool IsValidGridPosition(Vector2Int gridPos)
        {
            // 添加详细边界检查
            bool isValid = gridPos.x >= 0 && gridPos.x < _columns &&
                          gridPos.y >= 0 && gridPos.y < _rows;
            return isValid;
        }
        #endregion

        
        #region 动画状态
        /// <summary>
        /// 判断当前是否有动画正在播放
        /// </summary>
        public bool IsAnimating()
        {
            foreach (var cell in _cellsDict.Values)
            {
                if (cell != null && cell.IsAnimating())
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 矩阵整理
        /// <summary>
        /// 整理矩阵（下落+左移）
        /// </summary>
        /// <param name="useAnimation">是否使用动画效果</param>
        public void CompactMatrix(bool useAnimation = true)
        {
            _isAnimationEnabled = useAnimation;
            CompactColumns();
            CompactColumnCells();
        }

        /// <summary>
        /// 整理列（左移空白列）
        /// </summary>
        private void CompactColumns()
        {
            var validColumns = new List<int>();

            // 1. 找出所有有效列（至少有一个未消除的单元格）
            for (int x = 0; x < _columns; x++)
            {
                bool isEmptyColumn = true;
                for (int y = 0; y < _rows; y++)
                {
                    var cell = GetCell<CellCtrl_ZeroSum>(new Vector2Int(x, y));
                    if (cell != null)
                    {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (!isEmptyColumn) validColumns.Add(x);
            }

            // 2. 重新排列有效列到左侧
            // 创建临时字典保存新位置
            var newCells = new Dictionary<Vector2Int, CellCtrl>();
            
            for (int newX = 0; newX < validColumns.Count; newX++)
            {
                int originalX = validColumns[newX];
                if (newX == originalX)
                {
                    // 保留原位置的数据
                    for (int y = 0; y < _rows; y++)
                    {
                        var pos = new Vector2Int(newX, y);
                        if (_cellsDict.TryGetValue(pos, out var cell))
                        {
                            newCells[pos] = cell;
                        }
                    }
                    continue;
                }

                // 移动整列到新位置
                for (int y = 0; y < _rows; y++)
                {
                    var oldPos = new Vector2Int(originalX, y);
                    var newPos = new Vector2Int(newX, y);
                    
                    if (_cellsDict.TryGetValue(oldPos, out var cell))
                    {
                        // 更新单元格实际位置
                        cell.SetPos(newPos, _isAnimationEnabled);
                        // 更新到新位置
                        newCells[newPos] = cell;
                        // 同步更新单元格的坐标记录
                        cell.CurrentPos = newPos;
                    }
                }
            }
            
            // 更新字典并清空旧数据
            _cellsDict = newCells;
        }

        /// <summary>
        /// 整理单元格下落
        /// </summary>
        private void CompactColumnCells()
        {
            for (int x = 0; x < _columns; x++)
            {
                var columnCells = new List<CellCtrl_ZeroSum>();
                
                // 收集当前列未消除的单元格（从下往上）
                for (int y = 0; y < _rows; y++)
                {
                    var cell = GetCell<CellCtrl_ZeroSum>(new Vector2Int(x, y));
                    if (cell != null)
                    {
                        columnCells.Add(cell);
                    }
                }

                // 重新排列到列底部
                // 先移除所有旧位置
                foreach (var cell in columnCells)
                {
                    _cellsDict.Remove(cell.CurrentPos);
                }
                
                // 重新排列到列底部
                int newY = 0;
                foreach (var cell in columnCells)
                {
                    var newPos = new Vector2Int(x, newY++);
                    // 设置新位置（强制更新）
                    cell.SetPos(newPos, _isAnimationEnabled);
                    // 立即更新位置记录
                    cell.CurrentPos = newPos;
                    // 添加到字典
                    _cellsDict[newPos] = cell;
                }

                // 清理上方空单元格
                for (int y = newY; y < _rows; y++)
                {
                    var pos = new Vector2Int(x, y);
                    if (_cellsDict.ContainsKey(pos))
                    {
                        _cellsDict.Remove(pos);
                    }
                }
            }
        }

        /// <summary>
        /// 移除并销毁指定位置的单元格
        /// </summary>
        public void RemoveCell(Vector2Int pos)
        {
            if (_cellsDict.TryGetValue(pos, out var cell))
            {
                // 先禁用再销毁
                cell.gameObject.SetActive(false);
                Destroy(cell.gameObject);
                _cellsDict.Remove(pos);
            }
        }
        #endregion
    }
}
